import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/widgets/image/xindong_image_add_widget.dart';

// 图片网格视图
class XinDongImageGridView extends StatelessWidget {
  final List dataList; // 数据源
  final int maxCount; // 最大数量，默认0，不限制
  final int columns; // 最大数量，默认0，不限制
  final double spacing; // 横纵向间距，默认8.0
  final double radius; // 圆角弧度半径，默认8.0
  final double aspectRatio; // 宽高比，默认1.0
  final EdgeInsetsGeometry? padding; // 填充
  final Function()? onTapAddition; // 添加图片点击回调，为null时不能添加图片
  final IndexedWidgetBuilder itemBuilder; // Item构建

  const XinDongImageGridView(
      {Key? key,
      required this.dataList,
      required this.maxCount,
      required this.columns,
      required this.spacing,
      required this.radius,
      this.aspectRatio = 1.0,
      this.padding,
      this.onTapAddition,
      required this.itemBuilder})
      : super(key: key);

  // 获取图片数量，添加图片会多1个添加的item，总数在【0，maxCount】区间
  int get itemCount {
    int count = dataList.length + (onTapAddition == null ? 0 : 1);
    if (maxCount == 0) {
      return max(0, count);
    }
    return max(0, min(count, maxCount));
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      itemCount: itemCount,
      padding: padding,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        childAspectRatio: aspectRatio,
        // 子Widget宽高比例
        crossAxisCount: columns,
        // 一行的Widget数量
        crossAxisSpacing: spacing,
        // 水平间距
        mainAxisSpacing: spacing,
      ),
      itemBuilder: (BuildContext context, int index) {
        // 添加图片时调用
        if (onTapAddition != null && index == dataList.length) {
          return XinDongImageAddWidget(radius: radius, onTap: onTapAddition);
        } else {
          return PhysicalModel(
            color: DZColors.coverColor,
            borderRadius: BorderRadius.circular(radius),
            clipBehavior: Clip.antiAlias,
            child: itemBuilder(context, index),
          );
        }
      },
    );
  }
}
